package com.anji.plus.gaea.inf.exception;

import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.code.ResponseCode;
import com.anji.plus.gaea.inf.constant.ResEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;

@Order(1)
@RestControllerAdvice
public class InfExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MessageSource messageSource;

    /**
     * 业务异常
     * @param exception
     * @return
     */
    @ExceptionHandler(InfException.class)
    public ResponseBean infException(InfException exception){
//        logger.error("inf-exception：{}", exception.getMessage());
        //返回值构建
        String code = exception.getCode();
        if (null == code || "".equals(code)) {
            code = ResponseCode.FAIL_CODE;
        }
        String message = exception.getMessage();
        try {
            message = messageSource.getMessage(code, exception.getArgs(), LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            String msg = ResEnum.getMsg(code);
            if (msg != null) {
                message = msg;
            }
            if (null != message && !"".equals(message)) {
                Object[] args = exception.getArgs();
                if (args != null && args.length > 0) {
                    message = MessageFormat.format(message, args);
                }
            }
        }
        return ResponseBean.builder().code(code).message(message).build();
    }

}
